//
//  LoginViewController.m
//  IMChat
//
//  Created by Admin on 2021/6/20.
//  Copyright © 2021年 TeamOne. All rights reserved.
//

#import "LoginViewController.h"
#import "FriendTableViewController.h"
#import "MeTableViewController.h"
#import  "UManager.h"
#import  "FManager.h"
#import  "MManager.h"
#import "LoginLoadingView.h"

@interface LoginViewController ()

//登录手机号
@property (weak, nonatomic) IBOutlet UITextField *tel;

//登录密码
@property (weak, nonatomic) IBOutlet UITextField *loginPsw;

//登录按钮属性
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

//登录按钮点击事件
- (IBAction)loginBtnClick:(id)sender;

//注册昵称
@property (weak, nonatomic) IBOutlet UITextField *zcName;

//注册号码
@property (weak, nonatomic) IBOutlet UITextField *zcTel;

//注册密码
@property (weak, nonatomic) IBOutlet UITextField *zcPsw;

//确认密码
@property (weak, nonatomic) IBOutlet UITextField *zcPswSure;

//注册按钮属性
@property (weak, nonatomic) IBOutlet UIButton *zcBtn;

//注册按钮点击事件
- (IBAction)zcBtnClick:(id)sender;

@end



@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //监听账号和密码
    [self.tel addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:(UIControlEventEditingChanged)];
    [self.loginPsw addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:(UIControlEventEditingChanged)];
    
    self.tel.text = [SAMKeychain passwordForService:@"userId" account:AppKey];
    
    //监听昵称、手机号、密码、确认密码
    [self.zcTel addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:(UIControlEventEditingChanged)];
    [self.zcName addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:(UIControlEventEditingChanged)];
    [self.zcPsw addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:(UIControlEventEditingChanged)];
    [self.zcPswSure addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:(UIControlEventEditingChanged)];
    
    //数据库调试
//    UManager *user=[[UManager alloc] init];
    //    FManager *friend=[[FManager alloc] init];
    //    MManager *message=[[MManager alloc] init];
    //   赋值变量，插入想要的字符串，另外，删查改条件是UserId，目前查和删条件注释了，要设的话去接口对应功能函数注释一下条件语句就行
    
    //调用对应功能 insert query update datadelete
    
    //        user->token=@"sdafaf";
    //        user->user_name=@"user_name";
    //        user->user_password=@"user_password";
    //        user->user_portraitUri=@"user_portraitUri";
    //        user->userId=@"userId";
//    [user datadelete];
//
    
    
    //        friend->friend_id=@"sdafaf";
    //        friend->friend_name=@"user_name";
    //        friend->friend_portraitUri=@"user_password";
    //        friend->remarks=@"user_portraitUri";
    //    [friend query];
    
    //            message->classname=@"sdafaf";
    //            message->content=@"user_name";
    //            message->dateTime=@"user_password";
    //            message->msgUID=@"user_portraitUri";
    //        [message insert];
    
}

//当文本框内容发生改变时调用，让手机号和密码框都有内容时，登录按钮才能用
- (void)textFieldValueChanged:(UITextField *)textField {
    //手机号和密码框都有内容时，登录按钮才能点击
    self.loginBtn.enabled = self.tel.text.length && self.loginPsw.text.length;
    
    //昵称、手机号、密码都有内容时，注册按钮才能点击
    self.zcBtn.enabled = self.zcName.text.length && self.zcTel.text.length && self.zcPsw.text.length && self.zcPswSure.text.length;
    NSLog(@"==========%@", textField.text);
}

//点击空白处回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

//登录按钮点击事件
- (IBAction)loginBtnClick:(id)sender {
    NSLog(@"你点击了登录按钮");
    
    //使登陆按钮不可点击
    self.loginBtn.enabled=0;
    
    //调用加载动画
    [LoginLoadingView showWithTitle:@"登录中" result:RequestLoading addToView:self.view];
    
    // 验证用户身份
    [TOAFHttpUtils verifyUserLogin:_tel.text withPassword:_loginPsw.text
     withBlock:^(NSString *verifyResult){
        if([verifyResult isEqualToString:@"success"]){
            NSLog(@"verifyResult：%@",verifyResult);
            
            // 获取远程融云token
            [TOAFHttpUtils requestRCIMToken:self->_tel.text withName:@"" withPortraitUri:@"" withBlock:^(NSString *tokenResult){
                if(![tokenResult isEqualToString:@"error"]){
                    NSLog(@"tokenResult：%@",tokenResult);
                    
                    // 连接融云IM
                    [TORongUtils connectRongIM:tokenResult
                                     withBlock:^(NSString *connectResult){
                        NSLog(@"connectResult：%@",connectResult);
                        // block的结果为success，登陆成功，进行窗口跳转
                        if([connectResult isEqualToString:@"success"]){
                            // 获取主线程队列
                            dispatch_async(dispatch_get_main_queue(),^{
                                
                                //设置动画时间间隔1秒
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    //使登录按钮可以选中
                                    self.loginBtn.enabled = self.tel.text.length && self.loginPsw.text.length;
                                    //加载动画结束
                                    [[LoginLoadingView shareInstance] jz_hide];
                                    // 设置窗口跳转
                                    [self showMainView];
                                });
                                
                            });
                        }else{
                            NSLog(@"融云IM连接失败！咋回事啊，怎么又出bug了QAQ");
                            [self alertTool:@"IM连接失败，请提供反馈获得帮助！！"];
                        }
                    }];
                    
                }else{
                    NSLog(@"Token获取失败，你的代码又出bug啦！！！");
                    [self alertTool:@"Token获取失败，请提供反馈获得帮助！！"];
                }
            }];
            
        }else{
            NSLog(@"登陆验证失败，用户名或密码输入有误！！！");
            //设置动画时间间隔1秒
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //使登录按钮可以选中
                self.loginBtn.enabled = self.tel.text.length && self.loginPsw.text.length;
                //加载动画结束
                [[LoginLoadingView shareInstance] jz_hide];
                // 调用封装好的弹窗工具
                [self alertTool:@"登陆验证失败，用户名或密码输入有误！！！"];
            });
            
        }
    }];
    
}

//显示主界面事件
-(void)showMainView
{
    MainTarBarViewController *mainVC = [[MainTarBarViewController alloc]init];
    [self presentViewController:mainVC animated:NO completion:nil];
}

//注册按钮点击事件
- (IBAction)zcBtnClick:(id)sender {
    NSLog(@"你点击了注册按钮");
    
    if([_zcPsw.text isEqualToString:_zcPswSure.text]){
        [TOAFHttpUtils userRegister:_zcTel.text withName:_zcName.text
          withPassword:_zcPsw.text withBlock:^(NSString *registerResult){
              if([registerResult isEqualToString:@"success"]){
//                  [self alertTool:@"注册成功！请返回登陆！"];
//                  self->_tel.text = self->_zcTel.text;
        //改动
        //调用加载动画
        [LoginLoadingView showWithTitle:@"注册成功" result:RequestLoading addToView:self.view];
                  
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                      //加载动画结束
                      [[LoginLoadingView shareInstance] jz_hide];
                      
                  });
                  
                  self->_tel.text = self->_zcTel.text;
                  
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                      //跳转回登录界面
        [self performSegueWithIdentifier:@"a" sender:self];
                      
                  });
                  
              }else if([registerResult isEqualToString:@"error-1001"]){
                  [self alertTool:@"注册失败！用户已注册！"];
                  self->_tel.text = self->_zcTel.text;
              }else{
                  [self alertTool:@"注册失败！出现了未知错误，请反馈！"];
              }
        }];
        
    }else{
        [self alertTool:@"两次密码输入不一致！！"];
    }
    
}

// 弹窗工具
- (void)alertTool:(NSString *)message{
    //先创建一个弹窗控制器 然后里面有title和message来提示需要的东西
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    //添加一个弹窗的action 活动可以是取消 可以是确认
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:NO completion:nil];
}

@end
